package com.happyfamily.springboot.crowdsourcingplatform.service.wang.impl;

import com.happyfamily.springboot.crowdsourcingplatform.base.result.Results;
import com.happyfamily.springboot.crowdsourcingplatform.dao.sun.AllianceDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.wang.ArbitrationDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.wang.CreditDao;
import com.happyfamily.springboot.crowdsourcingplatform.dao.wang.ExposureDao;
import com.happyfamily.springboot.crowdsourcingplatform.model.*;
import com.happyfamily.springboot.crowdsourcingplatform.service.wang.ArbitrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ArbitrationServiceImpl implements ArbitrationService
{

	@Autowired
	private ArbitrationDao arbitrationDao;
	@Autowired
	private ExposureDao exposureDao;
	@Autowired
	private AllianceDao allianceDao;
	@Autowired
	private CreditDao creditDao;
	//修改昵称
	@Override
	public String changeName(String uid, String uname)
	{
		int index=arbitrationDao.changeName(uid, uname);
		String res="error";
		if (index>0)
		{
			res="success";
		}
		return res;
	}

	//修改地址
	@Override
	public String changeAddress(String uid, String uaddress)
	{
		int index=arbitrationDao.changeAddress(uid, uaddress);
		String res="error";
		if (index>0)
		{
			res="success";
		}
		return res;
	}

	//修改个人介绍
	@Override
	public String changeStory(String uid, String ustory)
	{
		int index=arbitrationDao.changeUstory(uid, ustory);
		String res="error";
		if (index>0)
		{
			res="success";
		}
		return res;
	}

	//订单申请仲裁
	@Transactional(rollbackFor=Exception.class)
	@Override
	public String applyArbitration(String oid,String cause)
	{
		Orders orders=arbitrationDao.orderDetails(oid);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String atime=sdf.format(new Date());
		String res="error";
		int index=arbitrationDao.addArbitration(oid,orders.getNeedid()+"",cause,atime);
		if (index>0)
		{
			index=arbitrationDao.changeStatus(oid,"6");
			if (index>0)
			{
				arbitrationDao.addOrderForm(oid,atime,"订单仲裁介入中");
				res="success";
			}
		}
		return res;
	}

	//查看仲裁处理的订单
	@Override
	public Results<Arbitration> arbitrationTable(Integer startP,Integer endP,String starttime, String endtime,String arbitrationType, HttpServletRequest request)
	{
		SecurityContextImpl securityContext=(SecurityContextImpl)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String uaccount=securityContext.getAuthentication().getName();
		return Results.success(arbitrationDao.arbitrationCount(starttime,endtime,uaccount,arbitrationType).intValue(),arbitrationDao.arbitrationTable(startP,endP,starttime,endtime,uaccount,arbitrationType));
	}

	//查看仲裁投票表格
	@Override
	public Results<Arbitration> voteTable(Integer startP, Integer endP, String starttime, String endtime, HttpServletRequest request)
	{
		SecurityContextImpl securityContext=(SecurityContextImpl)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String uaccount=securityContext.getAuthentication().getName();
		return Results.success(arbitrationDao.voteCount(starttime,endtime,uaccount).intValue(),arbitrationDao.voteTable(startP,endP,starttime,endtime,uaccount));
	}


	//对订单进行仲裁投票
	@Transactional(rollbackFor=Exception.class)
	@Override
	public String vote(String aid, String operate,HttpServletRequest request)
	{
		SecurityContextImpl securityContext=(SecurityContextImpl)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		String uaccount=securityContext.getAuthentication().getName();
		//将投票用户插了投票关系表，避免重复投票
		int index=arbitrationDao.vote(aid,uaccount);
		//获取仲裁订单详情
		Arbitration arbitration=arbitrationDao.getVote(aid);
		String res="error";
		if (index>0){
			//赞同雇主
			if ("yes".equals(operate)){
				int v=(int)arbitration.getEmploywin()+1;
				arbitrationDao.employVote(aid,v+"");
			}
			//赞同服务商
			else{
				int v=(int)arbitration.getServicewin()+1;
				arbitrationDao.serviceVote(aid,v+"");
			}
			//获取投票后最新的仲裁订单详情
			arbitration=arbitrationDao.getVote(aid);
			//判断仲裁总票数是否等于5
			int sum=(int)arbitration.getEmploywin()+(int)arbitration.getServicewin();
			res="success";
			if (sum==5){
				//查看投标状态
				Tender tender=arbitrationDao.searchTender(arbitration.getNid());
				String saccount="";
				//联盟投标状态查看联盟账号
				if (tender.getTtype().equals("联盟投标")){
					saccount=arbitrationDao.searchSaccount(tender.getUserid()+"");
				}
				//个人投标状态查看个人账号
				else{
					saccount=arbitrationDao.searchAccount(tender.getUserid()+"");
				}
				//获取订单的价格
				double money=Double.valueOf(exposureDao.exposureDetails(arbitration.getOid()).getNmoney());
				//从平台暂存账户里面取出钱
				index=arbitrationDao.updataMoney(money);
				//雇主获胜的情况下
				if ((int)arbitration.getEmploywin()>(int)arbitration.getServicewin()){
					//进行仲裁结果的修改
					arbitrationDao.updataWin(aid,"雇主获胜");
					if (index>0){
						//将钱退回给雇主
						arbitrationDao.updataUser(money+"",arbitrationDao.needDetails(arbitration.getNid()).getNuseraccount());
						SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
						String stime=s.format(new Date());
						//流水账单记录插入
						arbitrationDao.addFlow("仲裁退款","-"+money,stime,"-"+money,uaccount,"44444444");
						//提交曝光申请
						arbitrationDao.addExposure(arbitration.getCause(),saccount,arbitration.getOid());
						//修改订单状态
						arbitrationDao.changeStatus(arbitration.getOid(),"11");
						//修改仲裁状态
						arbitrationDao.arbitrationStatus(aid,"11");
						//扣除违规服务商信用分
						SysUser sys=arbitrationDao.SUser(saccount);
						arbitrationDao.updataUserScore(saccount,(Integer.valueOf(sys.getUscore())-1)+"");
						creditDao.addCredit(saccount,"-1","服务商提供需求违规",Integer.valueOf(sys.getUscore())-1+"",stime);
						arbitrationDao.addOrderForm(arbitration.getOid(),stime,"仲裁结束，钱原路退回雇主账户");
						res="success";
					}
				}else{
					//修改服务商获胜的结果
					arbitrationDao.updataWin(aid,"服务商获胜");
					if (index>0){
						//计算平台提成百分点
						int point=Integer.valueOf(arbitrationDao.tariffPoint(arbitration.getOid()));
						//算的平台提成的钱
						double pointMoney=(point*money)/100;
						//服务商实际收到的钱
						double realMoney=money-(pointMoney);
						SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
						String stime=s.format(new Date());
						//从暂存账户中取出钱的记录
						arbitrationDao.addFlow("订单交易完成，对服务商打款","-"+money,stime,"-"+money,saccount,"44444444");
						//判断是否为联盟投标
						if (tender.getTtype().equals("联盟投标")){
							//通过联盟查找盟友
							List<User_alliance> list=allianceDao.getUsers(Long.valueOf(tender.getUserid()));
							List<SysUser> users=new ArrayList<>();
							for (User_alliance ua : list)
							{
								//判断联盟状态
								if(ua.getUastate().equals("运行中"))
								{
									//获取盟友的账号
									SysUser sysUser=arbitrationDao.SearchUser(ua.getUid()+"");
									users.add(sysUser);
								}
							}
							//计算每个盟友平均分的钱
							String mmoney=new DecimalFormat("#.00").format(((1.00*realMoney)/users.size()));
							for (int i = 0; i < users.size(); i++)
							{
								String ua=users.get(i).getUaccount();
								//进行数据库的更改
								arbitrationDao.updataUser(mmoney,ua);
								//从暂存账户中取出钱的记录
								arbitrationDao.addFlow("订单交易完成，盟主打款",mmoney,stime,mmoney,ua,saccount);
								//信用分的更改
								int us=Integer.valueOf(users.get(i).getUscore());
								String f="+1";
								String ns=us+"";
								if ( us< 100)
								{
									ns=(us+ 1) + "";
								} else
								{
									f="+0";
								}
								arbitrationDao.updataUserScore(ua, ns);
								creditDao.addCredit(ua, f, "交易完成", ns, stime);
							}
							//saccount=arbitrationDao.searchAllianceBank(arbitration.getNid());
							//arbitrationDao.updataBank(realMoney+"",saccount);
						}else
						{
							arbitrationDao.updataUser(realMoney+"",saccount);
							//信用分的更改
							int us=Integer.valueOf(saccount);
							String f="+1";
							String ns=us+"";
							if ( us< 100)
							{
								ns=(us+ 1) + "";
							} else
							{
								f="+0";
							}
							arbitrationDao.updataUserScore(saccount, ns);
							creditDao.addCredit(saccount, f, "交易完成", ns, stime);
						}

						//修改订单状态
						arbitrationDao.changeStatus(arbitration.getOid(),"4");
						//修改仲裁状态
						arbitrationDao.arbitrationStatus(aid,"4");
						//平台抽成存入数据库
						arbitrationDao.updataBank(pointMoney+"","66666666");
						//账单流水
						arbitrationDao.addFlow("需求完成，平台提成",money+"",stime,pointMoney+"","66666666",saccount);
						arbitrationDao.addOrderForm(arbitration.getOid(),stime,"仲裁结束，认定服务商交易符合正规流程，交易完成");
						res="success";
					}
				}
			}
		}
		return res;
	}

	/**
	 * 仲裁员列表
	 * @param startP
	 * @param endP
	 * @param aname
	 * @param aaccount
	 * @param userStatus
	 * @return
	 */
	@Override
	public Results<SysUser> userTable(Integer startP, Integer endP, String aname, String aaccount, String userStatus)
	{
		return Results.success(arbitrationDao.userCount(aname,aaccount,userStatus).intValue(),arbitrationDao.userTable(startP,endP,aname,aaccount,userStatus));
	}

	/**
	 * 后台对仲裁员的禁用启用操作
	 * @param uid
	 * @param operate
	 * @return
	 */
	@Override
	public String arbitratorOperate(String uid, String operate)
	{
		String res="error";
		int index=0;
		if (operate.equals("enable")){
			index=arbitrationDao.arbitratorOperate(uid,"1");
		} else
		{
			index=arbitrationDao.arbitratorOperate(uid,"2");
		}
		if (index>0)
		{
			res="success";
		}
		return res;
	}

	/**
	 * 后台员对仲裁的重置密码
	 * @param uid
	 * @param repass
	 * @return
	 */
	@Override
	public String repass(String uid, String repass)
	{
		String res="error";
		int index=arbitrationDao.repass(uid,repass);
		if (index>0)
		{
			res="success";
		}
		return res;
	}
}
